import { PlaneCamp, PlaneEvent } from "../Constant/Constant";
import PoolManager from "../Manager/PoolManager";
import BulletControl from "./BulletControl";

const { ccclass, property } = cc._decorator;

@ccclass
export default class EnemyControl extends cc.Component {

  @property(cc.SpriteFrame)
  dieSpritFrame = null

  @property(cc.SpriteFrame)
  defaultSpriteFrame = null

  @property(cc.AudioSource)
  effectAudioSource: cc.AudioSource = null

  @property
  speed: number = 200

  @property
  hp: number = 1

  @property
  score: number = 1

  private isDied = false

  update(dt: number) {
    if (this.isDied != true) {
      this.move(dt)
    }
  }

  public init() {
    this.isDied = false
    this.node.getComponent(cc.Sprite).spriteFrame = this.defaultSpriteFrame
  }

  /**
   * 敌机向下移动
   * @param dt 
   */
  private move(dt: number): void {
    this.node.y -= this.speed * dt

    // 超出屏幕销毁，防止内存泄漏
    if (this.node.y < -this.node.height) {
      PoolManager.instance.putNode(this.node)
    }
  }

  public die(): void {
    if (this.isDied) {
      return
    }
    this.isDied = true

    // 销毁音效
    this.effectAudioSource.play()
    // 发送击毁事件
    const event = new cc.Event.EventCustom(PlaneEvent.DIED, true)
    event.setUserData({ score: this.score })
    this.node.dispatchEvent(event);

    // 切换爆炸图片
    this.node.getComponent(cc.Sprite).spriteFrame = this.dieSpritFrame
    // 0.3s后销毁
    this.scheduleOnce(() => {
      PoolManager.instance.putNode(this.node)
    }, 0.3)
  }

  /**
   * 当碰撞产生的时候调用
   * @param  {Collider} other 产生碰撞的另一个碰撞组件
   * @param  {Collider} self  产生碰撞的自身的碰撞组件
   */
  onCollisionEnter(other: cc.Collider, self: cc.Collider): void {
    if (other.tag !== 0) { return }

    // 被玩家子弹击中后销毁
    const bulletCtrl = other.getComponent(BulletControl)
    if (bulletCtrl == null) return

    if (bulletCtrl.from === PlaneCamp.PLAYER) {
      this.hp--
      if (this.hp <= 0) {
        this.die()
      }
    }
  }
}
